<?php

class Employer_IndexController extends Kieumau_Controller_Employer
{
	public function abc(){
		return false;	
	}
	
    public function init()
    {
		parent::init();
		
    	try{
    		$dirTemplate = TEMPLATE_PATH;
    		$sectionConfig = 'template';
    		$fileConfig = 'default/template.ini';
    		$this->createTemplate($dirTemplate, $sectionConfig, $fileConfig );
    	}catch(Exception $ex){
    		echo "error: ".$ex->getMessage();
    		die;
    	}
    }
	
	public function preDispatch() {
		
		$ntd = new Zend_Session_Namespace ( 'employerntd' );			
		if (empty($ntd->employerntd)) {//Nếu chưa đăng nhập thì session sẽ rỗng
			$actionAllow = array('index','register','active','message');
			if (! in_array($this->_request->getActionName (), $actionAllow)) {
				$this->_redirect ( '/employer/index' );//Đưa sang trang index
			}
		}
	}

    public function indexAction()
    {
		$this->view->mainMenuFocus	  = "home";
		$this->view->submainMenuFocus = "";
		
    	$common_table = new Model_DbTable_Common();
    	$ntd = new Zend_Session_Namespace ( 'employerntd' );    	
    	$this->view->loggedin = false;
		
    	if(!empty($ntd->employerntd)) 
    		$this->view->loggedin = true;	//Đánh dấu là đã login rồi
    	
    	if ($this->getRequest ()->isPost ()) {
    		$formData = $this->getRequest()->getPost();    		
    		$isValid = $this->validateEmail($formData['employer']['email']);//Kiểm tra hợp lệ
    		
    		if($isValid){//Hợp lệ    			
    			$userInfo = $common_table->getColumn('employer',array('id','password','email','companyname','status'),' email = "'.$formData['employer']['email'].'"');//Lấy id, password, email, status
				   			
				if( (hash('sha512',$formData['employer']['password']) == $userInfo[0]['password']) &&  $userInfo[0]['status']==2){//Đúng pass, status = 2[đã active]
					//Hủy session của employee
					/*
					$auth = Zend_Auth::getInstance ();
    				$auth->clearIdentity ();
					/**/
					
    				require_once('Zend/Session.php');
					$seconds  = 60 * 60 * 24 * 7; // 7 ngày
					if ($formData['remmeberme'] == "checked")
						Zend_Session::RememberMe($seconds);
					else				
						Zend_Session::ForgetMe();
		
    				$ntd->employerntd['id'] 			= $userInfo[0]['id'];			//Ghi id vào session
    				$ntd->employerntd['email']  		= $userInfo[0]['email'];		//Ghi email vào session
    				$ntd->employerntd['companyname']  	= $userInfo[0]['companyname'];	//Ghi companyname vào session
					
    				
    				$this->view->loggedin 		= true;//Đánh dấu đã login
    			}elseif($userInfo[0]['status'] == 1)//Sai pass hoặc chưa active account
						$this->view->error 			= "This account didn't activate, please active it before login!";
					else{
						$this->view->error 			= "The email or password you entered is incorrect";						
					}
    		}else{//Không hợp lệ    			
					$this->view->error 				= "Email is invalid";				
    		}
    	}
    }
    
    public function loginAction(){
    	
    }
    
    
	public function logoutAction(){
    	$this->_helper->layout->disableLayout (); //Load file phtml vào
    	$this->_helper->viewRenderer->setNoRender ();
    	
    	$ntd = new Zend_Session_Namespace ( 'employerntd' );
    	$ntd->unsetAll();
    	
    	$this->_redirect ( '/employer/index' );
    }
    
    
    //ko hợp lệ, return false
    //Hợp lệ, return true;
    public function validateEmail($email){
    	$validator = new Zend_Validate_EmailAddress();
    	if (!($validator->isValid($email))) {//Không hợp lệ
    		return false;
    	}
    	return true;
    }
    
   
    public function registerAction(){
    	$common_table = new Model_DbTable_Common();
    	$this->view->com_size = $common_table->getAll('company_size');    	
				
    	if ($this->getRequest ()->isPost ()) {
    		$formData = $this->getRequest ()->getPost ();
    		
    		//validate
    		$error_code = $this->validateRegister($formData);
    		
    		if(empty($error_code)){
	    		//$formData['employer']['password'] = md5($formData['employer']['password']);
				$formData['employer']['password'] = hash('sha512',$formData['employer']['password']);
	    		$activekey = $common_table->generateActivekey ( $formData ['employer'] ['password'] );//Phát sinh active key
    			$formData['employer']['activekey'] = $activekey;										
				$formData['employer']['status'] = 1;				
				
				$formData['employer']['companyprofile'] = nl2br($formData['employer']['companyprofile']);//str_replace(array('\r\n', '\r'), '\n', $formData['employer']['companyprofile'] );
				$common_table->insertData('employer',$formData['employer']);//insert DB
				
				
				$mailto = $formData['employer']['email'];
				$subject = "Register successful for Kieumau";
				$baseUrl = "http://".$this->getRequest()->getHttpHost().$this->getFrontController()->getBaseUrl();
				$body = '<br/>
						Thank you for registering at the Kieumau.<br/>
						Before we can activate your account one last step must be taken to complete your registration.<br /><br />
						Please note - you must complete this last step to become a registered member.<br />
						You will only need to visit this URL once to activate your account.<br /> <br />
						To complete your registration, please visit this URL:' . $baseUrl . '/employer/index/active/key/' . $activekey.'/email/'.$formData['employer']['email'];
				$this->sendEmail($mailto, $subject, $body);
								
				$message = array();
				$message['message'] 	= 'You have registered successfully. Please check your email and follow our instructions';				
				$message['url'] 		= $baseUrl = "http://".$this->getRequest()->getHttpHost().$this->getFrontController()->getBaseUrl().'/employer';
				$message['redirect'] 	= false;
				$this->view->message = $message;				
    		}
    		else{//return notice
    			$this->view->formData = $formData;
    			$this->view->error_list = $this->convertErrorRegister($error_code);
    		}
    		
    	}
    }
    
	
	public function activeAction(){
    	$activekey		= $this->_request->getParam ( 'key' );
    	$email			= $this->_request->getParam ( 'email' );
    	$employer_table = new Employer_Model_DbTable_Employer();
    	$result 		= $employer_table->validateActive($activekey, $email);
		
		$message = array();					
		$message['url'] 		= $baseUrl = "http://".$this->getRequest()->getHttpHost().$this->getFrontController()->getBaseUrl().'/employer';		
		
    	if(!empty($result)){//Dữ liệu ok
    		if($result['status'] == 1)//Chưa update
    		{
				$message['message'] 	= 'Your account has been activated successfully!';						    			
    			$employer_table->updateStatus($result['id'],2);//Cập nhật status cho employee đó
    		}
    		elseif($result['status'] == 2)//Đã update
    			$message['message'] = "This account is already actived!";			
    	}
    	else//Dữ liệu sai
    		$message['message'] = "Your active key is invalid, please check again and make sure it is correct.";
		$message['redirect'] 	= false; 					
		$this->view->message = $message;
    }
 
    public function validateRegister($formData){
    	//Validate email hợp lệ
    	$error_code = array();
    	if(!($this->validateEmail($formData['employer']['email']))){//Không hợp lệ
    		$error_code[0] = 0;					//Emai không hợp lệ 	=> erorr 0
    	}
    	//Validate email tồn tại
    	$validator = new Zend_Validate_Db_NoRecordExists(
    			array(
    					'table' => 'employer',
    					'field' => 'email',
    			)
    	);
    	
    	if (!($validator->isValid($formData['employer']['email']))) {//Đã có trong database
    		$error_code[1] = 0;					//Email đã tồn tại			=> error 1
    	}
    	
    	//Validate độ dài password
    	if(strlen(trim($formData['employer']['password'])) == 0) 	$error_code[2] = true; 				//Trống -> Lỗi 2
    	if ($formData['employer']['password'] != $formData['passwordconfirm']) $error_code[3] = true; 	//Ko trùng nhau -> Lỗi 3
    	$length = strlen ($formData['employer']['password']);
    	if ($length < 6 || $length > 32)	$error_code[4] = true; 										//Ngắn hoặc dài quá -> Lỗi 4
    	
    	//Validate đã check vào i agree...
    	if($formData['condition'] != "agree")
    		$error_code[5] = true; 																		//Chưa đồng ý thỏa thuận -> Lỗi 5
    	
    	if(empty($formData['employer']['contactname'])){
    		$error_code[6] = true;																		//Chưa nhập contact name-> Lỗi 6
    	}
    	
    	if(empty($formData['employer']['mobile'])){
    		$error_code[7] = true;																		//Chưa nhập mobile-> Lỗi 7
    	}
    	
    	if(empty($formData['employer']['companyname'])){
    		$error_code[8] = true;																		//Chưa nhập companyname-> Lỗi 8
    	}
    	
    	if(empty($formData['employer']['companyaddress'])){
    		$error_code[9] = true;																		//Chưa nhập companyaddress-> Lỗi 9
    	}
    	if($formData['employer']['companysize_id'] ==0){
    		$error_code[10] = true;																		//Chưa chọn companysize-> Lỗi 10
    	}
    	
    	if(empty($formData['employer']['companysite'])){
    		$error_code[11] = true;																		//Chưa nhập companyname-> Lỗi 11
    	}
		
		if(empty($formData['employer']['companyprofile'])){
    		$error_code[12] = true;																		//Chưa nhập companyprofile-> Lỗi 12
    	}
    	return $error_code;
    }
    
    public function convertErrorRegister($error_code){
    	$error_string = array(
    			'0'=> 'This email is not valid.',
    			'1'=> 'This email is already in use!',
    			'2'=> 'Password can not be empty',
    			'3'=> 'Confirm password does not match',
    			'4'=> 'Password must between 6 and 32 characters',
    			'5'=> 'You have to accept our terms and conditions',
    			'6'=> 'Please enter contact name',
    			'7'=> 'Please enter mobile',
    			'8'=> 'Please enter company name',
    			'9'=> 'Please enter company address',
    			'10'=> 'Please choose company size',
    			'11'=> 'Please enter company website',
				'12'=> 'Please enter company profile'
    			
    	);
    	$error_converted = array();
    	foreach($error_code as $key=>$value)
    		$error_converted[$key]=$error_string[$key];
    	return 	$error_converted;
    }
    
    public function createjobAction(){
		$this->view->mainMenuFocus	  = "createJob";
		$this->view->submainMenuFocus = "";
		
    	$common_table = new Kieumau_Db_Common();
		$job_table = new Employer_Model_DbTable_Job();
		    	
    	//Lấy thông tin về company của employer hiện tại
    	$ntd = new Zend_Session_Namespace('employerntd');    	
    	$this->view->employerInfo = $common_table->getAll('employer','id= "'.$ntd->employerntd['id'].'"');
		
    	//Xóa hết các job của employer này mà status của nó là 0
		$job_table->removeJob( $ntd->employerntd['id'] );
		
		//Xư lý textbox company profile		
		$this->view->employerInfo[0]['companyprofile']  = str_replace('<br />', '', $this->view->employerInfo[0]['companyprofile'] );
		
		//Xử lý đường dẫn cho logo
    	if(empty($this->view->employerInfo[0]['logo'])){
    		$this->view->employerInfo[0]['logo'] = $this->view->dirImg."/86logo.png";
    	}else{
    		$this->view->employerInfo[0]['logo'] = $this->view->dirImg.$this->view->employerInfo[0]['logo'];
    	}

    	$this->view->com_size 				= $common_table->getAll('company_size');
    	$this->view->job_level 				= $common_table->getAll('job_level');
    	$this->view->salary_range 			= $common_table->getAll('salary_range');
    	$this->view->province 				= $common_table->getAll('province','name != "International"');
    	$this->view->job_category 			= $common_table->getAll('job_category');
    	$this->view->job_type 				= $common_table->getAll('job_type');

		$cv_lang_list 						= $common_table->getAll('language_for_employee');
			
		foreach($cv_lang_list as $oneItem)
			$selectBoxData [$oneItem['id']] = $oneItem['name'];	
		
		$this->view->cv_lang_list = $this->createSelect($selectBoxData ,'',$this->language->getMessages('en','language_require_cv_id'));						
		
    	$formData 							= array();
		$formData['companysize']  			= $this->view->employerInfo[0]['companysize_id'];//Lấy company size trong db
		$formData['job']['job_category_id'] = 1;//Xác định giá trị lúc load page cho job category là tất cả ngành nghề
		$formData['job']['job_type_id'] 	= 1;//Khởi tạo job type = bất kỳ
		
    	$this->view->formData		= $formData;
		
		
    	if ($this->getRequest ()->isPost ()) {
    		unset($formData);
    		$formData = $this->getRequest()->getPost();
    		
    		//Validate
    		$error_code = $this->validatePostJob($formData);
    		if(!$error_code){
	    		//OK, Insert data
	    		$formData['job']['employer_id']  = $this->view->employerInfo[0]['id'];
				
				//Xử lý textarea
				$formData['job']['description'] = nl2br($formData['job']['description'] );
				$formData['job']['requirement'] = nl2br($formData['job']['requirement'] );
				
				$formData['job']['deadline'] = $this->format_date($formData['job']['deadline'], '/');				
				
	    		$formData['job']['create_date'] = Date('Y-m-d');
	    		$formData['job']['expire_date'] = date('Y-m-d',strtotime("+1 months",strtotime($formData['job']['create_date'])));
	    		
				$formData['job']['logo'] = $formData['logo'];
				
	    		$lastid = $common_table->insertData('job',$formData['job']);			
				$this->_redirect('employer/index/jobpreview/jobid/'.$lastid);
    		}else{				
    			$this->view->formData = $formData;
    			$this->view->error_code = $error_code;
				Zend_Debug::dump($error_code);
				
    		}
    	}
    }
	
	
	function format_date($date, $delimiter = '/'){
		switch($delimiter){
			case '/' : 
				$arrayDate = explode($delimiter, $date);
				if(is_array($arrayDate) && count($arrayDate) == 3)
				$date = $arrayDate[2].'-'.$arrayDate[1].'-'.$arrayDate[0];
				break;
			case '-' : 
				$arrayDate = explode($delimiter, $date);
				if(is_array($arrayDate) && count($arrayDate) == 3)
				$date = $arrayDate[1].'/'.$arrayDate[2].'/'.$arrayDate[0];
			break;   			
		}
		return $date;
	}


	public function jobpreviewAction(){
		$common_table = new Kieumau_Db_Common();
		$job_table = new Employer_Model_DbTable_Job(); 
		
		$jobId = $this->_request->getParam ( 'jobid' );		
		//so sánh trong db xem có phải job này của employer này k
		
		$ntd = new Zend_Session_Namespace ( 'employerntd' );
		$emloyerId = $ntd->employerntd['id'];
		//Kiểm tra xem job này có phải của employer đang đăng nhập ko
		$permission = $job_table->validateJobOwner($jobId, $emloyerId );
		if($permission[0]['permission'] != 1){//Không được phép truy cập			
			//Kiểm tra trạng thái job hiện tại: Nếu đã post thì hiển thị link để xe
			$this->_redirect ( '/employer/index/warning' );			
		}/*
		elseif($permission[0]['status'] != 0){//Nếu được phép truy cập, nhưng job này đã post rồi, redirect sang trang hiển thị link để view detail.
			
			$this->_redirect ( '/employer/index/jobexists' );
		}
		/**/
				
		$jobInfo 				= $common_table->getAll('job',' id = ?', array( $jobId ) );//Toàn bộ thông tin về job
		$employerInfo			= $common_table->getAll('employer',' id = ?', array( $jobInfo[0]['employer_id'] ) );//Thông tin về công ty		
		
		$size					= $common_table->getColumn('company_size',array('name'),' id = ?',array($employerInfo[0]['companysize_id']));
		$employerInfo[0]['companySize']= $size[0]['name'];//Company size				
		
		
		$level 					= $common_table->getColumn('job_level',array('name'),' id = ?',array($jobInfo[0]['job_level_id']));
		$jobInfo[0]['level']	= $level[0]['name'];//Job level
		
		$salary 				= $common_table->getColumn('salary_range',array('name'),' id = ?',array($jobInfo[0]['salary_range_id']));
		$jobInfo[0]['salary']	= $salary[0]['name'];//Job salary
		
		$province				= $common_table->getColumn('province',array('name'),' id = ?',array($jobInfo[0]['province_id']));
		$jobInfo[0]['province']	= $province[0]['name'];//Province
		
		$category				= $common_table->getColumn('job_category',array('name'),' id = ?',array($jobInfo[0]['job_category_id']));
		$jobInfo[0]['category']	= $category[0]['name'];//Category
		
		$jobInfo[0]['deadline'] = date ( 'd/m/Y', strtotime ( $jobInfo[0]['deadline'] ) );//Deadline
		
		$language				= $common_table->getColumn(' language',array('name'),' id = ?',array($jobInfo[0]['language_require_cv_id']));
		if(!empty($language))
			$jobInfo[0]['language']	= $language[0]['name'];//Language
		
		
		//Xử lý textarea
		$jobInfo[0]['description'] 		= str_replace(array('\n'), '<br/>', $jobInfo[0]['description'] );
		
		$this->view->jobInfo 	= $jobInfo[0];
		$this->view->employerInfo = $employerInfo[0];

		$this->view->jobId = $jobId;
				
	}
    
	public function postjobAction(){
		$this->_helper->layout->disableLayout ();		                                         
		$this->_helper->viewRenderer->setNoRender ();
		$job_table = new Employer_Model_DbTable_Job();
		$result = array();
				
		$jobId = $this->getRequest ()->getPost ('jobId');	
		$command = 	$this->getRequest ()->getPost ('command');
		
		//Kiểm tra trạng thái của job này
		$status = $job_table->getStatus($jobId);
		$status = $status[0]['status'];
			
		
		if($status == 0){//Trạng thái  = 0: Hợp lệ vì vừa tạo			
			//Cập nhật trạng thái job này trong database
			$job_table->updateStatus($command, $jobId);//1 là chế độ draft - 2 là chế độ online.
			
			$result ['result'] ['code'] = 'OK';
			$result ['result'] ['message'] = 'Your job is posted successfully!';
		}
		
		elseif($status == 1){//Trạng thái = 1: k hợp lệ vì job này đã post rồi			
			if($command == 1){//Lưu vào draft
				$result ['result'] ['code'] = 'OK';
			}else{
				$job_table->updateStatus(2, $jobId);//1 là chế độ draft - 2 là chế độ online.
			
				$result ['result'] ['code'] = 'OK';
				$result ['result'] ['message'] = 'Your job is posted successfully!';
			}
		}
		elseif($status == 2){//Trạng thái = 2: k hợp lệ vì job này đang ở trong draft
			$result ['result'] ['code'] = 'NOK2';
			$result ['result'] ['message'] = 'This job was posted in the past!';
		}		
		elseif($status == 3){//Trạng thái = 3: k hợp lệ vì job này đã bị đánh dấu xóa
			$result ['result'] ['code'] = 'NOK3';
			$result ['result'] ['message'] = 'This job is marked deleted, you have to active it before post it online!';
		}
		
		$json = Zend_Json::encode ( $result );
		print_r ( $json );	
		/**/	
	}
	
    //Validate empty
    public function validatePostJob($formData){
		
    	$error_code = array();
		
    	//Empty
    	foreach($formData as $key=>$value){
    		if($key!="job"){
    			if(empty($value)){
    				$error_code[$key] = ucfirst($key)." can not be empty2";
    			}
    		}else{
    			foreach($value as $key2=>$value2){
    				if($key2 != 'language_require_cv_id' && empty($value2))
    					$error_code['job'][$key2] = ucfirst($key2)." can not be empty";
    			}
    		}
    	}
		
		if($formData['salary_range_id'] != 3){
			unset($error_code['salaryfrom']);
			unset($error_code['salaryto']);
		}
		
		//validate email
		if(empty($error_code['job']['email_for_application']) && !($this->validateEmail($formData['job']['email_for_application'])))
			$error_code['job']['email_for_application'] = "Email is invalid";
    	return $error_code;
    	
    	//validate ngày tháng không hợp lệ
		
    }
    
    public function convertErrorPostJob($error_code){
    	
    	
    }
	
	public function warningAction(){
		$this->view->message = "You don't have permission to view this content!";
		$this->view->disableRedirect = true;
	}
	
	public function dialogAction(){
		$this->_helper->layout->disableLayout ();
		$this->_helper->viewRenderer->setNoRender ();	
	}
	
	public function messageAction(){
		$message = array();
		$message['message'] 	= 'Your active key invalid, please check again and make sure it is correct.';
		$message['redirect'] 	= false;
		$message['url'] 		= $baseUrl = "http://".$this->getRequest()->getHttpHost().$this->getFrontController()->getBaseUrl().'/employer';
		$this->view->message = $message;	
	}
	
	public function searchresumeAction(){
		$this->view->mainMenuFocus	  = "searchResume";
		$this->view->submainMenuFocus = "";
		$beginSearch = true;//Đánh dấu cho biết là lần đầu vào trang web hay là đã click nút search
		$commonTable = new Kieumau_Db_Common();
		
		$selectBoxData = array();
		
/*Location*/
		$temp 	= $commonTable->getAll('province');		
		foreach($temp as $oneItem)
			$selectBoxData [$oneItem['id']] = $oneItem['name'];	
		$this->view->locationList = $this->createSelect($selectBoxData,"",'Any');
/*END Location*/

/*Resume Update*/
		unset($temp, $selectBoxData);
		$temp 	= $commonTable->getAll('cv_update_range');		
		foreach($temp as $oneItem)
			$selectBoxData [$oneItem['value']] = $oneItem['name'];	
		$this->view->cvUpdateRange = $this->createSelect($selectBoxData,"",'Any');
/*END Resume Update*/		
		
/*Language List*/
		unset($temp, $selectBoxData);
		$temp 	= $commonTable->getAll('cv_language');		
		foreach($temp as $oneItem)
			$selectBoxData [$oneItem['id']] = $oneItem['name'];	
		$this->view->languageList = $this->createSelect($selectBoxData,"",$this->language->getMessages('en','noPreference'));
/*END of Language List*/

/*IS POST*/
		if($this->getRequest()->isPost()){
			$formData = $this->getRequest()->getPost();
			$cvTable = new Employer_Model_DbTable_Cv();
			
			//Chuẩn lại dữ liệu
			if(isset($formData['x']))
				unset($formData['x']);
			if(isset($formData['y']))
				unset($formData['y']);
			Zend_Debug::dump($formData);
			//Thực hiện tìm kiếm dữ liệu
			if(isset($formData['search-exactly'])){//Nếu như có check vào search exactly
				$cvTable->searchResume($formData,'exactly');
			}
		}
		
		$this->view->beginSearch	= $beginSearch;
	}

}